package com.shj.web.handler;

import com.shj.model.ErrorInfo;
import com.shj.model.ResResult;
import com.shj.web.util.ResultUtil;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * @Description TODO 重写返回体处理类
 * @Author songhuajian
 * @Date 2020/3/26 14:39
 **/
@RestControllerAdvice
public class ResponseControllerAdvice implements ResponseBodyAdvice<Object> {

    @Override
    public boolean supports(MethodParameter methodParameter, Class<? extends HttpMessageConverter<?>> aClass) {
        // 如果接口返回的类型本身就是ResResult那就没有必要进行额外的操作，返回false
        return !methodParameter.getGenericParameterType().equals(ResResult.class);
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter methodParameter, MediaType mediaType, Class<? extends HttpMessageConverter<?>> aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
        // 如果为异常，则直接返回
        if (body instanceof ErrorInfo){
            return body;
        }
        // 封装成功返回
        return ResultUtil.resultSuccess(body);
    }
}
